package com.bf.electroplating.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.poi.xssf.usermodel.XSSFShape;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Excel图片读取工具类
 * 使用Apache POI直接读取Excel中的图片
 */
@Slf4j
public class ExcelImageReader {
    
    /**
     * 图片保存路径
     */
    private static final String IMAGE_SAVE_PATH = "uploads/rectification/";
    
    /**
     * 从Excel中读取所有图片并保存
     * 
     * @param inputStream Excel文件输入流
     * @return Map<"行号_列号", "图片保存路径">
     */
    public static Map<String, String> readAndSaveImages(InputStream inputStream) {
        Map<String, String> imagePathMap = new HashMap<>();
        
        try (Workbook workbook = WorkbookFactory.create(inputStream)) {
            // 读取第一个Sheet
            Sheet sheet = workbook.getSheetAt(0);
            
            // 获取所有图片
            if (sheet instanceof org.apache.poi.xssf.usermodel.XSSFSheet) {
                org.apache.poi.xssf.usermodel.XSSFSheet xssfSheet = (org.apache.poi.xssf.usermodel.XSSFSheet) sheet;
                XSSFDrawing drawing = xssfSheet.getDrawingPatriarch();
                
                if (drawing != null) {
                    List<XSSFShape> shapes = drawing.getShapes();
                    log.info("找到{}个图形对象", shapes.size());
                    
                    for (XSSFShape shape : shapes) {
                        if (shape instanceof XSSFPicture) {
                            XSSFPicture picture = (XSSFPicture) shape;
                            XSSFClientAnchor anchor = (XSSFClientAnchor) picture.getAnchor();
                            
                            // 获取图片所在的行和列
                            int row = anchor.getRow1(); // 起始行
                            int col = anchor.getCol1(); // 起始列
                            
                            // 获取图片数据
                            byte[] imageBytes = picture.getPictureData().getData();
                            
                            // 保存图片
                            String imagePath = saveImage(imageBytes, row, col);
                            if (imagePath != null) {
                                String key = row + "_" + col;
                                imagePathMap.put(key, imagePath);
                                log.info("读取图片：行{}，列{}，大小：{} bytes，保存路径：{}", 
                                        row, col, imageBytes.length, imagePath);
                            }
                        }
                    }
                }
            }
            
            log.info("成功读取{}张图片", imagePathMap.size());
            
        } catch (Exception e) {
            log.error("读取Excel图片失败", e);
        }
        
        return imagePathMap;
    }
    
    /**
     * 保存图片到本地
     */
    private static String saveImage(byte[] imageBytes, int row, int col) {
        FileOutputStream outputStream = null;
        try {
            // 创建保存目录
            String dateFolder = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String savePath = IMAGE_SAVE_PATH + dateFolder + "/";
            Path directoryPath = Paths.get(savePath);
            if (!Files.exists(directoryPath)) {
                Files.createDirectories(directoryPath);
            }
            
            // 生成文件名：行_列_uuid.jpg
            String fileName = String.format("row%d_col%d_%s.jpg", row, col, 
                    UUID.randomUUID().toString().replace("-", "").substring(0, 8));
            String fullPath = savePath + fileName;
            
            // 保存文件
            File file = new File(fullPath);
            outputStream = new FileOutputStream(file);
            outputStream.write(imageBytes);
            outputStream.flush();
            
            log.debug("图片保存成功：{}，大小：{} bytes", fullPath, imageBytes.length);
            return fullPath;
            
        } catch (Exception e) {
            log.error("保存图片失败", e);
            return null;
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception e) {
                log.error("关闭输出流失败", e);
            }
        }
    }
}

